package com.cskaoyan.service.admin.impl;


import com.cskaoyan.aliyun.AliyunUtils;
import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.service.admin.MarketStorageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Can
 * @since 2022/06/26 17:57
 */
@Service
public class MarketStorageServiceImpl implements MarketStorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Autowired
    AliyunUtils aliyunUtils;

    /**
     * 通过对象Key和对象名称查找对象
     *
     * @return 对象list
     * @author LC_R-SH
     * @since 2022/06/27 9:20
     */
    @Override
    public CommonData<MarketStorage> query(String key, String name, BasePageInfo info) {
        // 开启分页查询
        PageHelper.startPage(info.getPage(), info.getLimit());
        // 利用storageExample去查询 新建
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        // criteria 就是根据什么进行查询 新建
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        // 判断条件是否为空 不是空进行拼接 key是精确查找 name是模糊查找
        if (!StringUtils.isEmpty(key)) {
            key = key.trim();
            criteria.andKeyLike(key);
        }
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name.trim() + "%";
            criteria.andNameLike(name);
        }
        // 拼接deleteed 显示未删除数据
        criteria.andDeletedEqualTo(false);
        // 查询结果按id 逆序排列
        marketStorageExample.setOrderByClause("id desc");
        // 查询时需要调用example方法 传入对象
        List<MarketStorage> storageList = marketStorageMapper.selectByExample(marketStorageExample);
        // 利用pageHelper插件去封装查询结果
        PageInfo<MarketStorage> data = new PageInfo(storageList);
        return CommonData.data(data);
    }

    /**
     * 用于对象储存（上传图片）
     *
     * @param file
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/26 18:46
     */
    @Override
    @Transactional
    public BaseRespVo uploadImage(MultipartFile file) {
        // 先存储图片
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.indexOf("."));

        String filename = UUID.randomUUID().toString() + substring;

        // 本地
        // String filePath = "D:\\project2\\resource\\image";
        //
        // File destiny = new File(filePath + "\\" + filename);
        // if (!destiny.getParentFile().exists()) {
        //     destiny.getParentFile().mkdirs();
        // }
        // try {
        //     file.transferTo(destiny);
        // } catch (IOException e) {
        //     e.printStackTrace();
        //     return null;
        // }

        // 上传到云端
        try {
            aliyunUtils.fileUpload(filename, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将数据保存至storage表中
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(filename);
        marketStorage.setName(originalFilename);
        marketStorage.setSize((int) file.getSize());
        marketStorage.setType(file.getContentType());
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setUrl("http://"+aliyunUtils.getOss().getBucket() + "." + aliyunUtils.getOss().getEndPoint() +"/"+ filename);

        // 设置默认值为false 表示未删除
        // LC
        marketStorage.setDeleted(false);

        int insert = marketStorageMapper.insert(marketStorage);
        BaseRespVo respVo;
        if (insert == 1) {
            respVo = BaseRespVo.ok(marketStorage);
        } else {
            respVo = BaseRespVo.invalidData("上传失败");
        }
        return respVo;
    }

    /**
     * LC 修改 删除改为伪删除 仅修改deleted数据为true
     * 系统管理-对象存储模块的删除功能。
     * 增加更新时间
     *
     * @param marketStorage
     * @return java.lang.Integer
     * @author Yan Dexuan
     * @since 2022/06/27 17:05
     */
    @Transactional
    @Override
    public Integer delete(MarketStorage marketStorage) {
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        criteria.andIdEqualTo(marketStorage.getId());
        marketStorage.setId(null);
        marketStorage.setDeleted(true);

        marketStorage.setUpdateTime(new Date());
        int update = marketStorageMapper.updateByExampleSelective(marketStorage, marketStorageExample);
        // int affactRows = marketStorageMapper.deleteByPrimaryKey(marketStorage.getId());
        // if (affactRows > 0) {
        //     return 200;
        // }
        return update;
    }

    /**
     * 前端只能修改名称,
     * id为主键自增无法修改
     *
     * @param marketStorage
     * @return 影响行数
     */
    @Transactional
    @Override
    public MarketStorage update(MarketStorage marketStorage) {
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        Integer id = marketStorage.getId();
        criteria.andIdEqualTo(id);
        // 主键自增无法修改 设为null后更新
        marketStorage.setId(null);
        // 设定更新时间
        marketStorage.setUpdateTime(new Date());
        int update = marketStorageMapper.updateByExampleSelective(marketStorage, marketStorageExample);
        MarketStorage storage = marketStorageMapper.selectByPrimaryKey(id);
        return storage;

    }
}
